package com.jt.permission.controller;

import com.jt.base.exception.RRException;
import com.jt.base.utils.R;
import com.jt.shiro.ShiroTag;
import com.jt.shiro.ShiroUtils;
import com.jt.base.utils.PassWordDecrypt;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 */
@Controller
@RequestMapping("admin/sys/")
@Validated
public class LoginController {
    @Autowired
    private Producer producer;
    @Value("${admin.password.private.key}")
    private String privateKey;
    @Resource
    private ShiroTag shiroTag;
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/login")
    public R login(
            @Valid @NotEmpty(message = "用户名不能为空")  String username,
            @Valid @NotEmpty(message = "密码不能为空") String password,
            @Valid @NotEmpty(message = "验证码不能为空") String captcha) {
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            return R.error("验证码不正确");
        }

        try {
            Subject subject = ShiroUtils.getSubject();
            String passwordTemp =password.replaceAll("%2B","+");
            String decryptPassword = PassWordDecrypt.decrypt(passwordTemp,privateKey);
            UsernamePasswordToken token = new UsernamePasswordToken(username, decryptPassword);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error("账号或密码不正确");
        } catch (LockedAccountException e) {
            return R.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return R.error("账户验证失败");
        } catch (RRException e) {
            return R.error("验证码过期");
        }catch (Exception e){
            return R.error("服务错误");
        }
        return R.ok();
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public R logout() {
        ShiroUtils.logout();
        return R.ok();
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/getPermission")
    @ResponseBody
    public R getPermission( @Valid @NotEmpty(message = "权限前缀不能为空") String permission) {
        return shiroTag.wrapPermission(R.ok(),permission);
    }
}
